#!/usr/bin/env python
# -*- coding:utf-8 -*-
# http://g1879.gitee.io/drissionpagedocs/whatsnew/4_0/
# pip install DrissionPage==4.0.0b38
import os
import time

from DrissionPage import ChromiumPage
from DrissionPage import ChromiumOptions
from colorama import Fore, init


class Config:
    def __init__(self):
        self.browser_path = r"C:\Program Files\Twinkstar Browser\twinkstar.exe"
        self.info = ' '
        self.url = 'https://www.qq.com'
        self.introduce = f'''
        -------------[快鸟]   自动化浏览器----------------------
        使用的浏览器:{self.browser_path}
        
        '''

    def showinfo(self):
        # print(self.logo)
        print(self.introduce)


class Browser:
    def __init__(self, browser_path):
        self.browser_path = browser_path
        self.co = ChromiumOptions()
        self.co.set_browser_path(self.browser_path)
        self.page = ChromiumPage(addr_or_opts=self.co)

        self.tabs = []
        self.eles = {}

    # def start(self, url):
    #     # 创建页面对象，并启动或接管浏览器
    #     self.page = ChromiumPage(addr_or_opts=self.co)
    #     self.page.get(url)

    def open(self, url):
        self.tabs.append(self.page.new_tab(url))
        return self

    @property
    def newest_page(self):
        return self.page.get_tab(self.page.latest_tab)

    def download_path(self, path):
        self.page.set.download_path(path)
        return self

    def download(self, url):
        self.page.download(url)
        return self

    def show_title(self):
        print(self.tab.title)
        return self

    def max(self):
        self.page.set.window.max()
        return self

    def min(self):
        self.page.set.window.mini()
        return self

    def hide(self):
        self.page.set.window.hide()
        return self

    def show(self):
        self.page.set.window.show()
        return self

    def wait(self, num: int):
        self.page.actions.wait(num)
        return self

    def elements(self, k: str, v: str):
        ele = self.tab.eles(f'@{k}={v}')
        return ele

    @property
    def tab(self):  # 返回最新的标签页
        return self.page.get_tab(self.page.latest_tab)

    def download_all_img(self, tag):
        for i in tag.eles('t:img'):
            for j in ['png', 'jpg', 'jpeg', 'webp', 'gif', 'tiff']:
                if j in i.link:
                    self.page.download(i.link)

        return self


def download_video(page):
    player = page.ele('x://*[@id="post"]/article/div[3]/div')
    page.actions.wait(2).click(player)

    player.drag(50, 50, 2)

    player.click.at(40, 70)
    print('视频下载中.......')


def download_img(page):
    for picture in page('@itemprop=articleBody').eles('t:img'):
        picture.save(path=page.title)
        print('saving the  picture...')


def click_next(page):
    page.ele('text:下一篇').click()
    time.sleep(3)


def screenshot(ele, name='viewer'):
    ele.get_screenshot(name=name, scroll_to_center=True)


def tree(ele):
    init()
    e = ele
    print(f'{Fore.BLUE}{Fore.CYAN}<{e.tag}>  {Fore.RESET}{e.attrs}')
    __tree(e)


def __tree(ele: any, layer=6, has_next_brother=True, body=''):
    try:
        list_ele = ele.children(timeout=0.1)
    except:
        list_ele = []

    length = len(list_ele)
    body_unit = '│   ' if has_next_brother else '    '
    tail = '├───'
    new_body = body + body_unit

    if length > 0 and layer >= 1:
        has_next_brother2 = True
        for i in range(length):
            if i == length - 1:
                tail = '└───'
                has_next_brother2 = False
            e = list_ele[i]
            all_body = f'{Fore.BLUE}{new_body}{tail}{Fore.RESET}'

            print(f'{all_body}{Fore.CYAN}<{e.tag}>{Fore.RESET} ')
            try:
                tree_attr(e, all_body, has_next_brother2, layer)
            except:
                pass

            __tree(e, layer - 1, has_next_brother2, new_body)


def tree_attr(ele, body, has_next_brother=True, layer=3):
    e: dict = ele.attrs
    has_child = True if ele.child(timeout=0.2) else False
    if layer == 1:
        has_child = False

    part1 = '│' if has_next_brother else ' '
    part2 = '│' if has_child else ' '
    replace_part = part1 + '   ' + part2
    new_body = body.replace('├───', replace_part).replace('└───', replace_part)

    text = ele.text.split('\n')[0]
    if len(text) >= 1:
        e['inner_txt'] = text

    if len(e) > 0:

        max_k_len = max([len(key) for key in e.keys()])
        for k, v in e.items():
            key = Fore.YELLOW + str(k).ljust(max_k_len) + Fore.RESET

            print(new_body, ' ', key, ':', v)


if __name__ == '__main__':
    # 创建配置对象
    import sys

    config = Config()
    config.showinfo()
    arguments = sys.argv

    url = r'https://news.ifeng.com/'
    if len(arguments) > 1:
        if 'http://' in arguments[1] or 'https://' in arguments[1]:
            url = arguments[1]

    # 创建浏览器对象
    # browser = Browser(r"C:\Program Files\Twinkstar Browser\twinkstar.exe")
    browser = Browser(r"K:\360\360ChromeX\Chrome\Application\360ChromeX.exe")

    # 打开网址 并打印网址标题
    browser.open(url).show_title()
    # 浏览器最xiao化
    browser.min()
    page = browser.newest_page
    page.set.NoneElement_value("没找到")
    # 定位元素
    # print(page.html)
    e = page.ele('x:/html/body')
    tree(e)

    # 显示元素的结构树
    # tree_attr(e,body='├───')

